package com.web.selenium;

import com.web.imp.ElementPopulator;
import com.web.model.WebElement;
import com.web.model.WebPage;
import com.web.model.element.ElementFactory;
import com.web.model.element.WebButton;
import com.web.model.element.WebCheckBox;
import com.web.model.element.WebLink;
import com.web.model.element.WebTextField;
import com.web.selenium.element.SeleniumButton;
import com.web.selenium.element.SeleniumCheckBox;
import com.web.selenium.element.SeleniumLink;
import com.web.selenium.element.SeleniumTextField;

public class SeleniumElementFactory implements ElementFactory{

	private SeleniumWebBrowser browser;
	
	public SeleniumElementFactory(SeleniumWebBrowser browser){
		
		this.browser = browser;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends WebElement> T getElement(Class<T> type, String id) {

		T elementInstance = null;
		
		org.openqa.selenium.WebElement element = browser.findWebElement(id);
		
		if(type.equals(WebTextField.class)){
			
			elementInstance = (T) new SeleniumTextField(element);
		}
		else if(type.equals(WebButton.class)){
		
			elementInstance = (T) new SeleniumButton(element);
		}
		else if(type.equals(WebCheckBox.class)){
			
			elementInstance = (T) new SeleniumCheckBox(element);
		}
		else if(type.equals(WebLink.class)){
			
			elementInstance = (T) new SeleniumLink(element);
		}
		else
			throw new IllegalStateException(String.format("Couldn't create element '%s'", type));
		
		return elementInstance;
	}

	public void initElements(WebPage page) {
		
		new ElementPopulator(this).populateInstance(page);
	}
}
